<!--suppress JSVoidFunctionReturnValueUsed, JSUnresolvedVariable, NpmUsedModulesInstalled -->
<template>
  <div class="app-container">
    <el-button @click="addBanner()" size="small" type="success" class="el-icon-circle-plus" style="margin-bottom: 10px"> 添加轮播图</el-button>
    <el-button @click="batchChangeBannerState(1)" size="small" type="primary" class="el-icon-caret-top" style="margin-bottom: 10px">一键发布</el-button>
    <el-button @click="batchChangeBannerState(0)" size="small" type="warning" class="el-icon-caret-bottom" style="margin-bottom: 10px">一键下架</el-button>
    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="bannerList"
      :default-sort="{prop: 'gmtModified', order: 'descending'}"
      element-loading-text="数据加载中"
      border
      fit
      highlight-current-row>

      <el-table-column
        label="序号"
        width="60"
        align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column prop="title" label="名称" width="110" align="center"/>
      <el-table-column prop="linkUrl" label="链接" width="110" align="center"/>
      <el-table-column label="图片" width="520" align="center">

        <template slot-scope="scope">
          <el-upload
            class="avatar-uploader"
            :action="BASE_API+'/itservice/imageadmin'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess.bind(this,scope.row.id)"
            :before-upload="beforeAvatarUpload">
            <img :alt="scope.row.title" v-if="scope.row.imageUrl" :src="scope.row.imageUrl" class="avatar"
                 style="width: 500px; height: 300px" title="点击更换">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </template>

      </el-table-column>

      <el-table-column prop="sort" label="热度" sortable width="80" align="center"/>
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.state === 0 ? '未发布' : '已发布' }}
          <br>
          <el-switch
            title="更改状态"
            v-model="scope.row.state.toString()"
            style="margin-top:15px"
            active-value="1"
            inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeState(scope.row.id)"/>
        </template>
      </el-table-column>

      <el-table-column prop="gmtCreate" label="添加时间" sortable align="center"/>

      <el-table-column prop="gmtModified" label="修改时间" sortable align="center"/>


      <el-table-column label="操作" align="center" width="70">
        <template slot-scope="scope">
          <router-link :to="'/banner/add/'+scope.row.id">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              title="编辑轮播图"></el-button>
          </router-link>
          <br><br>
          <el-button
            type="success"
            icon="el-icon-picture"
            size="small"
            @click="showImage(scope.row.imageUrl)"
            title="查看轮播图"></el-button>
          <br><br>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="small"
            @click="removeBannerById(scope.row.id)"
            title="删除轮播图"></el-button>
        </template>

      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :current-page="page"
      :page-size="limit"
      :total="total"
      style="padding: 30px 0; text-align: center;"
      layout="total, prev, pager, next, jumper"
      @current-change="getList"
    />
  </div>

</template>

<script>
import bannerApi from '@/api/banner'

export default {

  // 写核心代码位置
  data() { // 定义变量和初始值
    return {
      bannerList: [], // 查询之后接口返回集合
      page: 1, // 当前页
      limit: 10000, // 每页记录数
      total: 0,
      BASE_API: process.env.BASE_API// 获取dev.env.js端口号
    }
  },

  created() {
    this.getList()
  },

  methods: {

    //改变状态
    changeState(id) {
      this.$confirm('确定更改该轮播图状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除成功
        bannerApi.changeState(id)
          .then(response => {
            // 提示信息
            this.$message({
              type: 'success',
              message: '轮播图状态更改成功!'
            })
            // 刷新并回到当前页
            this.getList()
          })
      })
    },

    //查看图片
    showImage(url) {
      window.open(url)
    },

    //添加Banner
    addBanner() {
      this.$router.push({path: '/banner/add'})
    },

    handleAvatarSuccess(idx, res, file, name) {
      console.log("============上传文件=============")
      console.log("idx = ", idx)
      console.log("res = ", res)
      console.log("file = ", file)
      console.log("name = ", name)
      console.log("res = ", res.data.url)
      console.log("bannerList = ", this.bannerList)
      let index = -1
      for (let i = 0; i < this.bannerList.length; i++) {
        if (idx === this.bannerList[i].id) {
          this.bannerList[i].imageUrl = res.data.url
          index = i
        }
      }
      console.log("bannerList = ", this.bannerList)

      bannerApi.updateBanner(this.bannerList[index])
        .then(response => {
          this.$message({
            message: "Banner上传成功",
            type: "success"
          })
        })
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },


    // 课程列表的方法
    // page=1
    getList(page = 1) {
      this.page = page // 分页修改参数
      //console.log(this.page)
      //console.log(this.limit)
      bannerApi.getPageBanner(this.page, this.limit)
        .then(response => {

          this.bannerList = response.data.items
          this.total = response.data.total

          this.$notify({
            message: "查询到" + this.bannerList.length + "张轮播图",
            type: "success"
          })

          console.log("============获取列表============")
          console.log(this.bannerList)
          console.log(this.total)
        })
    },

    // 删除Banner
    removeBannerById(bannerId) {
      this.$confirm('此操作将永久删除该Banner, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除成功
        bannerApi.removeBanner(bannerId)
          .then(response => {
            // 提示信息
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            // 刷新并回到当前页
            this.getList()
          })
      })
    },

    //一键发布
    batchChangeBannerState(state) {
      let upBannerNum = 0
      let downBannerNum = 0
      for (let i = 0; i < this.bannerList.length; i++) {
        if (this.bannerList[i].state===1) {
          upBannerNum++
        } else {
          downBannerNum++
        }
      }
      if (state===1) {
        if(downBannerNum===0) {
          this.$message({
            message: "当前无未上架轮播图！",
            type: "warning"
          })
          return
        }
        this.$confirm('当前有'+downBannerNum+'个轮播图未上架，是否一键上架这'+downBannerNum+'个轮播图？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          bannerApi.batchChangeBannerState(state)
            .then(response => {
              this.$message({
                message: downBannerNum+"个轮播图上架成功",
                type: "success"
              })
              this.getList()
            })
        })
      } else {
        if(upBannerNum===0) {
          this.$message({
            message: "当前无已上架轮播图！",
            type: "warning"
          })
          return
        }
        this.$confirm('当前有'+upBannerNum+'个轮播图已上架，是否一键下架这'+upBannerNum+'个轮播图？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          bannerApi.batchChangeBannerState(state)
            .then(response => {
              this.$message({
                message: upBannerNum+"个轮播图下架成功",
                type: "success"
              })
              this.getList()
            })
        })
      }
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
